package com.zhanglijie.theory.sigleThreadedExecutor;

import java.util.ArrayList;
import java.util.concurrent.Semaphore;

import ru.concerteza.util.db.springjdbc.CtzSpringJdbcUtils;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/7/22 0022 0:56
 */
public class FixThreadNumTest {
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(8);
        FixThreadNumTest test = new FixThreadNumTest();
        long start = System.currentTimeMillis();
        ArrayList<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            Thread t = new Thread(()->{
                try {
                    semaphore.acquire();//这个会判断是否能让线程执行，如果信号量用完了 当前线程阻塞。如果 获得 信号量-1
                    test.eat(finalI);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println("第"+ finalI +"客人用餐完毕，请下位进来用餐=========》");
                    semaphore.release();//归还使用的信号量 唤醒阻塞的线程
                }
            }) ;

            t.start();//start必须放在join前面
            threads.add(t);
        }
        for (int i = 0; i < threads.size(); i++) {
         threads.get(i).join();
        }
        System.out.println("总共耗时+"+(System.currentTimeMillis()-start));

    }

    private void eat(int finalI) throws InterruptedException {
        System.out.println("》》》》》第"+finalI+"进行用餐");
        Thread.sleep(5000);
    }
}
